package com.excilys.capicsoubank.webservices.soap.callback;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import com.excilys.capicsoubank.entities.User;

@Component
public class PasswordCallback implements CallbackHandler {

	@Autowired
	private UserDetailsService userService;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Override
	public void handle(Callback[] callbacks) throws IOException,
			UnsupportedCallbackException {

		WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];

		if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {
			UserDetails userDetails = userService.loadUserByUsername(pc
					.getIdentifier());
			String password = userDetails.getPassword();

			User user = new User.Builder().username(pc.getIdentifier()).build();

			Authentication authentication = new UsernamePasswordAuthenticationToken(
					user, password);
			authentication = authenticationManager.authenticate(authentication);

			SecurityContextHolder.getContext()
					.setAuthentication(authentication);

			pc.setPassword(password);

		}
	}
}
